package com.moming.web;

import com.moming.pojo.User;
import com.moming.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    UserService userService= new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1.接收用户信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取复选框数据
        String remeber = request.getParameter("remeber");
        //调用service层获取结果
        User user = userService.login(username, password);
        response.setContentType("text/html;charset=utf-8");
        if(user!=null){
            //判断用户是否勾选记住密码
            //创建cookie对象
            //Cookie c_username = new Cookie("username", username);
            //URLEncoder.encode(username,"utf-8")解决账号是中文乱码
            Cookie c_username = new Cookie("username", URLEncoder.encode(username,"utf-8"));
            Cookie c_password = new Cookie("password", password);
            //访问此路径下的都带cookie
            c_username.setPath("/moming");
            c_password.setPath("/moming");
            if("1".equals(remeber)){
                //设置cookie存活时间一天
                c_username.setMaxAge(60*60*24);
                c_password.setMaxAge(60*60*24);
            }else {
                //销毁cookie
                c_username.setMaxAge(0);
                c_password.setMaxAge(0);
            }
            //发送cookie
            response.addCookie(c_username);
            response.addCookie(c_password);
            //将登录成功的user对象存储到session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //存在,登录成功,跳转Servlet
            String contextPath = request.getContextPath();
            //重定向
            response.sendRedirect(contextPath+"/successServlet");


        }else {
            //不存在,登录失败,跳转的登录页面
            request.setAttribute("msg", "用户名或密码错误");
            //转发
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
